let isDark;
window.onload = function () {

    internationalizes();
    setImg('./img/iconD.png');

    if (window.hilink) {
        setDarkMode();
        getSystemInfo();
        listeningBleChange();
    }
    //注册30s以上，提示超时，如果连接成功，断开连接
    const OVERTIME_SEC_IOS = 60;
    const OVERTIME_SEC_ANDROID = 30;
    setTimeout(() => {

        this.document.getElementById("btnContainer").style.cssText = "display:flex";
        if (isDark) {
        // if (true) {
            this.document.getElementById("btnContainer").style.background = "#000000";
            this.document.getElementsByClassName("btn")[0].style.background = "rgba(255,255,255,0.1)";
            this.document.getElementsByClassName("btn")[0].style.color = "#317AF7";

        }
        this.document.getElementById("alertContainer").style.cssText = "display:block";
        this.document.getElementById("progressContainer").style.cssText = "display:none";

        if (mac && mac.length > 0) {
            console.log("断开设备" + mac);
            closeConnection(mac);
            isTimerouted = true;
        }
        this.document.getElementsByClassName("connectHint")[0].style.cssText = "display:none";
    }, isIOS ? OVERTIME_SEC_IOS * 1000 : OVERTIME_SEC_ANDROID * 1000);
    let i = 1;
    let timer = setInterval(() => {
        if (i >= 91) {
            clearInterval(timer);
            return
        }
        this.document.getElementById("progressValue").innerHTML = i;
        i++;
    }, 150);

}
let isTimerouted = false;
var isIOS = false;
var deviceId = '';
var mac = '';
var serviceId = '0000180a-0000-1000-8000-00805f9b34fb';
var characteristicId = '00002a23-0000-1000-8000-00805f9b34fb';

var SERVICE_UUID = '0000fda0-0000-1000-8000-00805f9b12ea';
var CHARACTERISTIC_NOTIFY_UUID = '0000fda5-0000-1000-8000-00805f9b12ea';
let CHARACTERISTIC_WRITE_NORESPONSE_UUID = '15f1e602-a277-43fc-a484-dd39ef8a9100';
let SERVICE_DEV_INFO_UUID = '15f1e600-a277-43fc-a484-dd39ef8a9100';
let CHARACTERISTIC_DEV_INFO_UUID = '15f1e601-a277-43fc-a484-dd39ef8a9100';
let SERVICE_REGISTER_UUID = '15f1e500-a277-43fc-a484-dd39ef8a9100';
let CHARACTERISTIC_REGISTER_UUID = '15f1e501-a277-43fc-a484-dd39ef8a9100';
let fwv = '1.0';
let hwv = '1.0';
isDark = false;

// 暗黑模式适配
function setDarkMode() {
    try {
        isDark = window.hilink.getDarkMode() === 2;
    } catch (error) {

    }
    if (isDark) {
    // if (true) {
        this.document.getElementsByClassName("connect-content")[0].style.background = "#000000";
        this.document.getElementById("app").style.background = "#000000";
        this.document.getElementsByClassName("detail")[0].style.color = "rgba(255,255,255,0.86)";
        this.document.getElementsByClassName("failConnect")[0].style.color = "rgba(255,255,255,0.86)";
        this.document.getElementsByClassName("progress")[0].style.color = "rgba(255,255,255,0.86)";
        this.document.getElementsByClassName("progressDes")[0].style.color = "rgba(255,255,255,0.66)";
        this.document.getElementsByClassName("failImg")[0].src = './img/ic_yichang_dark.png';
        this.document.getElementsByClassName("failImg")[0].style.opacity = "0.86";
        this.document.getElementsByClassName("deviceImg")[0].style.opacity = "0.86";
    }
}

// 监听蓝牙变化,主动打开或关闭蓝牙会触发
function listeningBleChange() {
    window.hilink.onBluetoothAdapterStateChange('onBlueToothAdapterStateChangeCallback')

    window.onBlueToothAdapterStateChangeCallback = res => { // 监听蓝牙状态回调函数
        let data = JSON.parse(res)
        console.log('打开/关闭蓝牙开关:', data.available)
        if (data.available && !isTimerouted) { // 检测到蓝牙打开
            getUnRegisterDeviceFun();
        } else { // 监测到蓝牙被关闭
            openBlueTooth();
        }
    }
}

// 获取手机系统信息,判断手机操作系统是 Android 还是 iOS
function getSystemInfo() {
    console.log('新协议接口>>>>>>连接', window.hilink.connectBle)
    console.log('新协议接口>>>>>>订阅', window.hilink.subscribeBleEvent)
    window.hilink.getSystemInfoSync('getSystemInfoSyncCallBack')
    window.getSystemInfoSyncCallBack = info => {
        let data = JSON.parse(info);
        console.log('设备信息~~~~~~~~~~~~~~~~', JSON.stringify(data));
        if (data.platform === "iOS") {
            console.log("iOS设备")
            isIOS = true;
        } else {
            console.log("andorid设备")
            isIOS = false;
        }
        getBluetoothAdapterState();
    }
}

// 当前蓝牙模块状态
function getBluetoothAdapterState() {
    window.hilink.getBluetoothAdapterState("getBlueToothAdapterStateCallback")

    window.getBlueToothAdapterStateCallback = res => {
        let data = JSON.parse(res);
        console.log('蓝牙模块当前状态:', data.available);
        console.log("是否超时" + isTimerouted);
        if (data.available && !isTimerouted) { // 蓝牙处于打开状态,进入注册流程
            getUnRegisterDeviceFun();
        } else { // 蓝牙处于打开状态
            openBlueTooth();
        }
    }
}

// 打开蓝牙
function openBlueTooth() {
    window.hilink.openBluetoothAdapter()
}

function setDevTypeImage(name) {
    if (name !== null) {
        let type = parseInt(name.substr(name.length - 6, 2));
        console.log("type", type);
        switch (type) {
            case 0:
                this.document.getElementsByClassName("deviceImg")[0].src = './img/img_device_blue.png'
                break;
            case 1:
                this.document.getElementsByClassName("deviceImg")[0].src = './img/img_device.png'
                break;
            case 2:
                this.document.getElementsByClassName("deviceImg")[0].src = './img/img_device_red.png'
                break;
            default:
                this.document.getElementsByClassName("deviceImg")[0].src = './img/img_device_blue.png'
        }
    }
}

// 订阅蓝牙事件
function subBleEvents(deviceId, mac) {
    window.hilink.subscribeBleEvent(deviceId, mac, 'subBleEventsCallback')
    window.subBleEventsCallback = res => {
        console.log('订阅蓝牙事件回调', res)
        let subEventRes = null
        try {
            subEventRes = JSON.parse(res)
        } catch (error) {
            subEventRes = res
        }
        if (subEventRes.type === 'ConnectionStateChange') {
            console.log('蓝牙连接成功-------')
            setTimeout(() => {
    //             updateUIafterConnected.call(this);
                console.log("开始写入命令---》》》》》》", deviceId, mac);
                window.hilink && window.hilink.sendCommand(deviceId, mac, 'fwv', '', 'getNetCfgVerCb');
                if (isIOS) {
                    processAfterWrite();
                } else {
                    window.getNetCfgVerCb = res => {
                        console.log('fwv 获取设备信息', res)
                    }
                }
            }, 3000);
        }
    }
}

// 获取当前页面被选中的未注册的设备,拿去注册
function getUnRegisterDeviceFun() {
    window.hilink.getCurrentUnregisteredDevice('getCurrentUnregisteredDeviceCallback')

    window.getCurrentUnregisteredDeviceCallback = res => {
        console.log("unregisteredDevice", JSON.stringify(res));
        let data = JSON.parse(res);
        console.log('获取注册设备信息:', data);
        deviceId = data.deviceId
        console.log('获取安卓的MAC地址(ios的uuid):', data.deviceId);
        //为不同型号设备设置图片
        setDevTypeImage(data.localName);
        if (!isTimerouted) {
            if (isIOS) { // IOS设备注册
                getIOSdevices();
            } else {    // 安卓设备注册
                mac = deviceId;
                subBleEvents(deviceId, mac)
                connectDevice();
            }
        }
    }
}

function closeConnection(mac) {
    window.hilink && window.hilink.disconnectBle(deviceId, mac, 'disconnectBleCb');
    window.disconnectBleCb = res => {
        console.log('断连结果----', res)
    }
}

function updateUIafterConnected() {
    document.getElementById("connectHint").style.cssText = "display:flex";
    if (isDark) {
        this.document.getElementById("connectHint").style.color = "rgba(255,255,255,0.86)";
    }
    document.getElementById("progressContainer").style.cssText = "display:none";
}

function processAfterWrite() {
    console.log('开始读取设备信息>>>>>---')
    //监听蓝牙设备的特征值变化
    // window.hilink && window.hilink.onBLECharacteristicValueChange("bleCharacteristicValueChangeCallBack");
    // window.bleCharacteristicValueChangeCallBack = function (charicValueResult) {
    //     console.log("监听蓝牙设备的特征值变化", "charicValueResult", JSON.stringify(charicValueResult));
    //     let charicReult = JSON.parse(charicValueResult);//获取到特征值最新的值
    //     if (charicReult.data) {
    //         if (charicReult.data.toLowerCase() === CryptoJS.MD5("a0060101" + mac.substr(mac.length - 5).replace(":", "").toUpperCase()).toString()) {
                window.readDevInfoCallback = (res) => {
                    console.log('读取信息----->>>', res)
                    let devInfo = hextoString(JSON.parse(res).data);
                    devInfo = JSON.parse(JSON.stringify(devInfo));
                    devInfo = eval("(" + devInfo + ")");
                    // console.log("认证通过，读取设备信息", charicReult.data, devInfo, devInfo.fwv, devInfo.hwv);

                    fwv = devInfo.fwv;
                    // hwv = devInfo.hwv;
                    hwv = "XH-001-MB-S-V1.0";
                    console.log("读取devInfo完成", fwv, hwv);
                    registerBleDevice(mac);
                }
                window.hilink.readBLECharacteristicValue(deviceId, SERVICE_DEV_INFO_UUID, CHARACTERISTIC_DEV_INFO_UUID, 'readDevInfoCallback');
        //     } else {
        //         //认证失败
        //         // console.log("认证失败", charicReult.data.toLowerCase(), CryptoJS.MD5("a0060101" + mac.substr(mac.length - 5).replace(":", "").toUpperCase()).toString());
        //     }
        // }
    // }
    // let retcode = window.hilink.notifyBLECharacteristicValueChange(deviceId, SERVICE_UUID, CHARACTERISTIC_NOTIFY_UUID, true);
    // console.log("notify retcode", retcode);
}

// 先监听，后连接
function connectDevice() {
    console.log('开始尝试连接蓝牙设备...', deviceId);
    // window.hilink.onBLEConnectionStateChange('onBLEConnectionStateChangeCallback'); // 监听蓝牙设备连接结果
    // window.onBLEConnectionStateChangeCallback = res => {
    //     let data = JSON.parse(res);
    //     console.log('蓝牙设备连接结果', data.connected);
    //     if (data.connected) { // 连接成功，先收到按键确认的notify后，再去到云端注册设备。

            // setTimeout(() => {
    //             updateUIafterConnected.call(this);
                // let target = isIOS ? deviceId : mac;
    //             console.log("ble write target ", target);
            //     window.hilink && window.hilink.writeBLECharacteristicValue(target, SERVICE_UUID, CHARACTERISTIC_WRITE_NORESPONSE_UUID, "a00a0101", "writeRegisterProcessCallBack");
            //     if (isIOS) {
            //         processAfterWrite();
            //     } else {
            //         window.writeRegisterProcessCallBack = res => {
            //             processAfterWrite();
            //         }
            //     }
            // }, 3000);


    //     } else { // 连接失败，重新获取未注册的设备，进行连接。
    //         getUnRegisterDeviceFun();
    //     }
    // }

    // window.hilink.createBLEConnection(deviceId); // 连接蓝牙设备

    window.hilink.connectBle(deviceId, mac, 'connectBleCallback')
    window.connectBleCallback = res => {
        console.log('新协议连接回调-----', res)
    }
}

// 注册设备,注册成功后会在APP设备列表页显示设备
function registerBleDevice(mac) {
    // console.log('开始注册蓝牙设备:', mac, fwv, hwv);
    window.hilink.registerBleDevice(mac, fwv, hwv, 'registerBleDeviceCallback')
    window.registerBleDeviceCallback = res => {
        const s = "1".charCodeAt().toString(16);
        let target = isIOS ? deviceId : mac;
        window.hilink.writeBLECharacteristicValue(target, SERVICE_REGISTER_UUID, CHARACTERISTIC_REGISTER_UUID, s, "writeRegisterResultCallBack");
        console.log("注册动作ret", target)
        window.writeRegisterResultCallBack = res => {
            console.log("写入注册结果完成" + DataChange(res));
        }
    }
}

// IOS发现附近蓝牙
function getIOSdevices() {
    console.log('IOS,发现附近蓝牙设备,获取其MAC地址')
    window.hilink.onBluetoothDeviceFound("onBluetoothDeviceFoundCallBack");

    window["onBluetoothDeviceFoundCallBack"] = info => {
        let data = JSON.parse(info);

        let macInfo = getMAC(data); // 处理设备信息，获取设备MAC

        if (macInfo[0] === 1) {
            mac = macInfo[1]
            connectDevice();
        } else if (macInfo[0] === 2) {
            // console.log('IOS,本蓝牙设备无advertisData字段，直接去连接设备,可能无法做鉴权');
            getMacByRead();
            // connectDevice()
        }
        subBleEvents(deviceId, mac)
    }

    window.hilink.startBluetoothDevicesDiscovery([], 0, 1);
}

// IOS处理附近蓝牙设备信息，获取其MAC地址
// 0 未扫描到设备, 1 匹配到设备, 2匹配到设备没有mac地址
function getMAC(data) {
    console.log('IOS,开始进行设备匹配...')
    if (data.deviceId === deviceId) { // 附近设备MAC地址，与当前设备UUID匹配
        console.log("IOS,匹配到蓝牙设备:" + data.deviceId + ' ,并停止扫描.')

        window.hilink.stopBluetoothDevicesDiscovery();// 关闭扫描

        console.log('IOS,匹配到的蓝牙设备信息：', data);

        if (data.advertisData) {
            let advertisData = data.advertisData;
            advertisData = advertisData.replace(/ /g, '');
            advertisData = advertisData.slice(advertisData.length - 13, advertisData.length - 1).toLocaleUpperCase();
            let macAdress = this.analysisMac(advertisData);
            console.log("ios mac", macAdress);
            return [1, macAdress];
        } else {
            return [2, '']
        }
    }
    return [0, ''];

}

//
function getMacByRead() {
    // // 监听蓝牙特征值变化
    window.hilink.onBLECharacteristicValueChange("onBLECharacteristicValueChangeCallback")
    window.onBLECharacteristicValueChangeCallback = res => {
        console.log(res);
    }

    // 连接设备
    window.hilink.createBLEConnection(deviceId)
    window.hilink.onBLEConnectionStateChange('onIOSBLEConnectionStateChangeCallback')
    window.onIOSBLEConnectionStateChangeCallback = res => {
        console.log('IOS onIOSBLEConnectionStateChangeCallback...')
        let data = JSON.parse(res)
        if (data.connected) {
            let timer = null
            clearInterval(timer);
            timer = setInterval(() => {
                let status = window.hilink.notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, true)
                console.log('notify status:', status)
                if (status === 0) {
                    clearInterval(timer);
                    window.hilink.readBLECharacteristicValue(deviceId, serviceId, characteristicId, 'readBLECharacteristicValueCallback')
                    window.readBLECharacteristicValueCallback = res => {
                        let tempMac = JSON.parse(res).data;
                        tempMac = analysisMac(tempMac)

                        // console.log('TEMP mac 地址:', tempMac);

                        // registerBleDevice(tempMac)
                        // updateUIafterConnected();
                        // setTimeout(() => {
                        //     //监听蓝牙设备的特征值变化
                        //     window.hilink && window.hilink.onBLECharacteristicValueChange("bleCharacteristicValueChangeCallBack");
                        //     window.bleCharacteristicValueChangeCallBack = function (charicValueResult) {
                        //         console.log("监听蓝牙设备的特征值变化", "charicValueResult", JSON.stringify(charicValueResult));
                        //         let charicReult = JSON.parse(charicValueResult);//获取到特征值最新的值
                        //         if (charicReult.data) {
                        //             if (charicReult.data.toLowerCase() === CryptoJS.MD5("a0060101" + mac.substr(mac.length - 5).replace(":", "").toUpperCase()).toString()) {
                        //                 registerBleDevice(tempMac);
                        //             }
                        //         }
                        //     }
                        //     let retcode = window.hilink.notifyBLECharacteristicValueChange(deviceId, SERVICE_UUID, CHARACTERISTIC_NOTIFY_UUID, true);
                        //     // console.log("notify retcode", retcode);
                        // }, 3000);

                    }
                }
            }, 200)
        } else {
            console.log("断开连接")
            // getUnRegisterDeviceFun();
        }
    }

}

function finishDeviceActivity() {
    window.hilink && window.hilink.finishDeviceActivity();
}

// 中英文翻译
function internationalizes() {
    this.currentLanguage = (function getAppLanguage() {
        // 判定规则:如果不是以'zh-'开始则显示为en-US
        let language,
            defualtLanguage = 'zh-CN';
        // let language = window.hilink.getAppLanguage();
        let reg = /^zh-/i;
        if (navigator && navigator.language) {
            language = reg.test(navigator.language) ? defualtLanguage : 'en-US';
            console.log("navigator获取的语言", language);
        } else {
            language = defualtLanguage;
            console.log("默认语言", language);
        }
        try {
            if (!language) {
                language = window.hilink.getAppLanguageSync();
                console.log("getAppLanguageSync语言", language);
            }
        } catch (e) {
            console.log("没有getAppLanguageSync接口", e);
        }
        return language;
    })();

    if (this.currentLanguage !== 'zh-CN') {
        this.document.getElementsByClassName("progressDes")[0].innerHTML = 'Connecting…'
        this.document.getElementsByClassName("connectHint")[0].innerHTML = 'Long press the power button for 5 seconds to connect'
        this.document.getElementsByClassName("failConnect")[0].innerHTML = 'Unable to connect'
        this.document.getElementsByClassName("details")[0].innerHTML = 'While connecting, make sure:'
        this.document.getElementsByClassName("details")[1].innerHTML = '1.The phone\'s Bluetooth is enabled.'
        this.document.getElementsByClassName("details")[2].innerHTML = '2.The device is within 5 meters of the phone.'
        this.document.getElementsByClassName("details")[3].innerHTML = '3.The phone is connected to the Internet.'
        this.document.getElementsByClassName("details")[4].innerHTML = '4.The device is not paired with the current account before.'
        this.document.getElementsByClassName("btn")[0].innerHTML = 'Try again'
    }
}

// 设备图片
function setImg(path) {
    var ImgObj = new Image(); //判断图片是否存在

    ImgObj.src = path;

    if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
        console.log('图片存在')
    } else {
        console.log('图片不存在，使用默认图片')
        this.document.getElementsByClassName("deviceImg")[0].src = './img/iconD.png'
    }

}

// 解析mac地址
function analysisMac(str) {
    str = this.hexArarryAddSpace(str, 2)
    let arr = str.split(' ')
    arr.reverse()
    let result = '';
    arr.map(item => {
        result += item + ':'
    })
    result = result.slice(0, result.length - 1)
    return result
}

function hexArarryAddSpace(str, split_len = 2) {
    /** 16进制字符串 每2个字符用一个空格隔开 **/
    let result = '';
    for (let i = 0; i < str.length; i += split_len) {
        if (result !== '') result += ' ';
        result += str[i] + str[i + 1];
    }
    return result;
}

let hextoString = function (hex) {
    var arr = hex.split("");
    var out = ""
    for (var i = 0; i < arr.length / 2; i++) {
        var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]
        var charValue = String.fromCharCode(tmp);
        out += charValue
    }
    return out
}
let DataChange = function (res) {
    let data;
    try {
        data = JSON.parse(res);
    } catch (err) {
        try {
            let dataStr = res.replace(/:"{/g, ':{');
            dataStr = dataStr.replace(/\\/g, '');
            data = JSON.parse(dataStr);
        } catch (error) {
            try {
                let dataStr = res.replace(/:"{/g, ':{');
                dataStr = dataStr.replace(/\\/g, '');
                dataStr = dataStr.replace(/\s/g, '');
                dataStr = dataStr.replace(/(^\s*)|(\s*$)/g, '');
                dataStr = dataStr.replace(/}",/g, '},');
                dataStr = dataStr.replace(/}"/g, '}');
                data = JSON.parse(dataStr);
            } catch (error) {
                let dataStr = res.replace(/:"{/g, ':{');
                dataStr = dataStr.replace(/\\/g, '');
                dataStr = dataStr.replace(/\s/g, '');
                dataStr = dataStr.replace(/}",/g, '},');
                dataStr = dataStr.replace(/}"/g, '}');
                dataStr = dataStr.replace(/"{/g, '{');
                dataStr = dataStr.replace(/]"/g, ']');
                dataStr = dataStr.replace(/"\[/g, '[');
                dataStr = dataStr.replace(/\\/g, '');
                dataStr = dataStr.replace(/\n/g, '');
                dataStr = dataStr.replace(/\r/g, '');
                dataStr = dataStr.replace(/\t/g, '');
                dataStr = dataStr.replace(/(^\s*)|(\s*$)/g, '');
                dataStr = dataStr.replace(/}"/g, '}');
                dataStr = dataStr.replace(/\s+/g, "");
                dataStr = dataStr.replace(/:"\[/g, ':[');

                let sSpace = unescape('%01');  //特殊空格
                dataStr = dataStr.replace(new RegExp(sSpace, 'g'), "");
                dataStr = dataStr.replace(/\u0001/g, '');
                // console.log('解析失败:',dataStr);
                data = JSON.parse(dataStr);
            }
        }
    }
    return data;
}
